//
//  BLHomeViewController.m
//  blanket
//
//  Created by Mac on 2017/12/4.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "BLHomeViewController.h"
#import "KLSharePresentController.h"
#import "BLHomeCollectionViewCell.h"
#import "BLHomeTableViewCell.h"
#import "BLClothShareViewController.h"
#import "BLClothCustomViewController.h"
#import "BLClothMangeViewController.h"
#import "BLMineOrderViewController.h"
#import "BLClosthWashViewController.h"
#import "BLShopingPointViewController.h"
#import "BLShopingViewController.h"
#import "BLBannerModel.h"
#import "BLServiceShopModel.h"
#import "KLMessageChatViewController.h"
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "BLShopingDetailViewController.h"
#import "BLCustomCenterViewController.h"
#import "BTLifeViewController.h"
#import "BLCaiJiCenterViewController.h"
#import "BLHotelHomeViewController.h"
#import "BLWathClosthHomeViewController.h"
@interface BLHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout,TencentSessionDelegate>
@property(nonatomic, strong) STAdvertingScrollView               *adverView;
@property(nonatomic, strong) UICollectionView                     *collectionView;
@property(nonatomic, strong) NSArray                     *collectionViewdataSouce;
@property(nonatomic, strong) NSMutableArray                     *tableViewDataSouce;
@property(nonatomic, strong) TencentOAuth                     *tencentOAuth ;
@property(nonatomic, strong) NSString                     *shareStr;
@property(nonatomic, strong) NSMutableArray                     *kefuArray;
@property(nonatomic, strong) BLUserModel                     *userModel;

@property(nonatomic, strong) NSArray                     *cidArray;/**< <##> */
@end

@implementation BLHomeViewController
#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    [self st_setRightItemWithImage:[UIImage imageNamed:@"分享(1)"]];
    [self configSubView];
    [self sendcidRequest];
    self.tencentOAuth = [[TencentOAuth alloc] initWithAppId:TencentQQAppid andDelegate:self];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self sendLoadBannerReuqest];
    [self sendShareRequest];
    [self sendKefuRequest];
    [self sendMyInfoRequest];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{

    UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 200)];
    self.adverView = [[STAdvertingScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 0.5 *UIScreenWidth ) andWithArray:@[@"banner1",@"banner1",@"banner1",@"banner1",@"banner1"] handle:^(NSInteger num) {
        
    }];
    self.adverView.pageControll.bottom = self.adverView.height - 15;
    self.adverView.pageControll.currentPageIndicatorTintColor = [UIColor whiteColor];
    self.adverView.pageControll.pageIndicatorTintColor = KL_BlueBackGroundColor;
    self.adverView.pageControll.centerX = UIScreenWidth / 2;
    self.adverView.canAutoScroll = YES;
    self.adverView.time = 3;
    [headerView addSubview:self.adverView];
    __weak typeof(self) weakSelf =  self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf sendShopsRequest];
        [weakSelf sendcidRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
    flow.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flow.minimumLineSpacing = 0;
    flow.minimumInteritemSpacing = 0;
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.adverView.bottom, UIScreenWidth, [BLHomeCollectionViewCell cellHeight] * 2) collectionViewLayout:flow];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[BLHomeCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    [headerView addSubview:self.collectionView];
    self.collectionView.scrollEnabled = NO;
    [self.collectionView st_showBottomShadow];
    headerView.height = self.collectionView.bottom;
    self.tableView.tableHeaderView = headerView;
    self.collectionViewdataSouce = @[
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"铺盖生活" titleName:@"铺盖生活"],
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"布草洗涤" titleName:@"布草洗涤"],
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"布草间" titleName:@"布草间"],
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"商城" titleName:@"采集商城"],
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"酒店" titleName:@"铺盖酒店"],
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"订单中心" titleName:@"订单中心"],
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"积分部" titleName:@"积分部"],
                                     [[BLHomeCollectionViewModel alloc] initWithImageName:@"客服中心" titleName:@"客服中心"]];
    [self.collectionView reloadData];
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.collectionViewdataSouce.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(SCREEN_WIDTH/4, [BLHomeCollectionViewCell cellHeight]);
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BLHomeCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    item.model = self.collectionViewdataSouce[indexPath.row];
    return item;
}
#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
  
    if (!self.userModel) {
         [SVProgressHUD showInfoWithStatus:@"请稍后"];
        return;
    }
    // 普通会员 限制
    if (self.userModel.card.integerValue == 3) {
        if (indexPath.row == 1 ||
            indexPath.row == 4 ) {
            //普通会员，不能进入 洗涤，增加和库存
            [SVProgressHUD showInfoWithStatus:@"现在您是普通会员，暂不能进行该操作哦"];
            return;
        }

    }
    
    
    if (indexPath.row == 0) {
        BTLifeViewController * vc = [BTLifeViewController new];
        vc.bannerArray = self.adverView.imageUrlsArray;
        vc.cidArray = self.cidArray;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 1) {
        [self.navigationController pushViewController:[BLWathClosthHomeViewController new] animated:YES];
    }
    if (indexPath.row == 2) {
        [self.navigationController pushViewController:[BLClothCustomViewController new] animated:YES];
    }
    if (indexPath.row == 3) {
        //商城
        [self.navigationController pushViewController:[BLCaiJiCenterViewController new] animated:YES];
        
    }
    if (indexPath.row == 4) {
        //铺盖酒店
        BLHotelHomeViewController * vc = BLHotelHomeViewController.new;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.row == 5) {
        //订单中心
        [self.navigationController pushViewController:[BLMineOrderViewController new] animated:YES];
    }
    if (indexPath.row == 6) {
        //积分商城
        [self.navigationController pushViewController:[BLShopingPointViewController new] animated:YES];
    }
    if (indexPath.row == 7) {
        //客服
        [self.navigationController pushViewController:BLCustomCenterViewController.new animated:YES];

        
//        if (!self.kefuArray.count) {
//             [SVProgressHUD showInfoWithStatus:@"暂无客服在线哦"];
//            return;
//        }
//        NSString * phone = self.kefuArray.firstObject;
//        KLMessageChatViewController * vc = [[KLMessageChatViewController alloc] initWithConversationChatter:phone conversationType:EMConversationTypeChat];
//        [self.navigationController pushViewController:vc animated:YES];
        
    }
    
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.tableViewDataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [BLHomeTableViewCell cellHeight];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 44;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)];
    sectionHeader.backgroundColor = [UIColor whiteColor];
    STButton * line = [[STButton alloc] initWithFrame:CGRectMake(15, 0, 4, 22)
                                                title:nil
                                           titleColor:nil
                                            titleFont:14
                                         cornerRadius:0
                                      backgroundColor:BL_BlueBackGroundColor
                                      backgroundImage:nil
                                                image:nil];
    line.centerY = 22;
    [sectionHeader addSubview:line];
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(line.right + 20, 0, 200, 44)
                                                     text:@"服务商家"
                                                textColor:BL_firstTextColor
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    
    [sectionHeader addSubview:titleLable];
    return sectionHeader;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    BLHomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[BLHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.model = self.tableViewDataSouce[indexPath.row];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BLShopModel * model = self.tableViewDataSouce[indexPath.row];
    BLShopingDetailViewController * vc = [BLShopingDetailViewController new];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    KLSharePresentController * vc = [[KLSharePresentController alloc] initWithHandle:^(NSString *chosedIde) {
        NSLog(@"%@",chosedIde);
        if (!self.shareStr.length) {
            [self sendShareRequest];
        }
        if ([chosedIde isEqualToString:@"QQ"]) {
            UIImage * image = [UIImage imageNamed:@"质量"];
            NSData * data = UIImagePNGRepresentation(image);
            QQApiURLObject * obj = [QQApiURLObject objectWithURL:[NSURL URLWithString:self.shareStr]
                                                           title:@"铺盖科技下载地址"
                                                     description:@"下载铺盖科技加入我们吧"
                                                 previewImageData:data targetContentType:QQApiURLTargetTypeNews];
            SendMessageToQQReq *req = [SendMessageToQQReq
                                       reqWithContent:obj];
            
            //向QQ发送消息，查看是否可以发送
            QQApiSendResultCode sent = [QQApiInterface sendReq:req];
            
            //[SVProgressHUD showInfoWithStatus:@"正在开发中，敬请期待"];
        }else{
            SendMessageToWXReq  *req = [SendMessageToWXReq new];
            req.text = self.shareStr;
            req.bText = YES;
            req.scene = WXSceneSession;
            if ([chosedIde isEqualToString:@"朋友圈"]) {
                req.scene = WXSceneTimeline;
            }
            [WXApi sendReq:req];
        }

    }];
    [self presentViewController:vc animated:NO completion:nil];
}
#pragma mark --TencentSessionDelegate
- (void)responseDidReceived:(APIResponse*)response forMessage:(NSString *)message{
    
    
}
- (void)onResp:(QQBaseReq *)resp{
    
    
}
#pragma mark --NetWork Method
- (void)sendLoadBannerReuqest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/getBannerAction"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * dataArray =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 NSMutableArray * urls = [NSMutableArray new];
                                                 NSMutableArray * models = [NSMutableArray new];
                                                 for (NSDictionary * dataDic in dataArray) {
                                                     BLBannerModel * model =  [BLBannerModel mj_objectWithKeyValues:dataDic];
                                                     [urls addObject:model.img_url];
                                                     [models addObject:model];
                                                 }
                                                 self.adverView.imageUrlsArray = urls;
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendShopsRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/getIndexAction"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 NSArray * dataArray =  responseObject[@"data"];
                                                 //NSLog(@"json = %@",dataDic.mj_JSONString);
                                                  self.tableViewDataSouce = [NSMutableArray new];
                                                 for (NSDictionary * dataDic in dataArray) {
                                                     BLShopModel * model =  [BLShopModel mj_objectWithKeyValues:dataDic];
                                                     [self.tableViewDataSouce addObject:model];
                                                 }
                                                 [self.tableView.mj_header endRefreshing];
                                                 [self.tableView reloadData];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [self.tableView reloadData];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendShareRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/shareAction"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 self.shareStr =  responseObject[@"data"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}

- (void)sendKefuRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/service"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 self.kefuArray = [NSMutableArray new];
                                                 NSArray * array =responseObject[@"data"];
                                                 for (NSDictionary * dataDic in array) {
                                                     [self.kefuArray addObject:dataDic[@"mobile"]];
                                                 }
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendMyInfoRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php/Api/Basics/MemberListAction"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 self.userModel = [BLUserModel mj_objectWithKeyValues:responseObject[@"data"]];
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
//获取采集商城分类
- (void)sendcidRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:debugToken forKey:@"token"];
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/api/hotel/cate"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {

                                                 self.cidArray = responseObject[@"data"];
                                                 
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                                     [self sendcidRequest];
                                                 });
                                             }];
}
@end

